import * as echarts from 'echarts'

// 通用图表配置
export const commonChartOption = {
  backgroundColor: 'transparent',
  textStyle: {
    color: '#fff',
    fontFamily: 'Microsoft YaHei'
  },
  grid: {
    left: '10%',
    right: '10%',
    top: '15%',
    bottom: '15%',
    containLabel: true
  },
  tooltip: {
    trigger: 'axis',
    backgroundColor: 'rgba(0, 0, 0, 0.8)',
    borderColor: '#1890ff',
    borderWidth: 1,
    textStyle: {
      color: '#fff'
    }
  },
  legend: {
    textStyle: {
      color: '#fff'
    },
    top: '5%'
  }
}

// 柱状图配置
export const getBarOption = (data) => {
  return {
    ...commonChartOption,
    xAxis: {
      type: 'category',
      data: data.categories,
      axisLine: {
        lineStyle: {
          color: '#1890ff'
        }
      },
      axisLabel: {
        color: '#fff',
        rotate: data.categories.length > 10 ? 45 : 0
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: '#1890ff'
        }
      },
      axisLabel: {
        color: '#fff'
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(24, 144, 255, 0.1)'
        }
      }
    },
    series: data.series.map((item, index) => ({
      name: item.name,
      type: 'bar',
      data: item.data,
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#1890ff' },
          { offset: 1, color: '#36cfc9' }
        ])
      },
      barWidth: '60%'
    }))
  }
}

// 折线图配置
export const getLineOption = (data) => {
  return {
    ...commonChartOption,
    xAxis: {
      type: 'category',
      data: data.categories,
      boundaryGap: false,
      axisLine: {
        lineStyle: {
          color: '#1890ff'
        }
      },
      axisLabel: {
        color: '#fff'
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: '#1890ff'
        }
      },
      axisLabel: {
        color: '#fff'
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(24, 144, 255, 0.1)'
        }
      }
    },
    series: data.series.map((item) => ({
      name: item.name,
      type: 'line',
      data: item.data,
      smooth: true,
      lineStyle: {
        color: '#1890ff',
        width: 2
      },
      itemStyle: {
        color: '#36cfc9'
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(24, 144, 255, 0.3)' },
          { offset: 1, color: 'rgba(24, 144, 255, 0.05)' }
        ])
      }
    }))
  }
}

// 饼图配置
export const getPieOption = (data) => {
  return {
    ...commonChartOption,
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)',
      backgroundColor: 'rgba(0, 0, 0, 0.8)',
      borderColor: '#1890ff',
      borderWidth: 1,
      textStyle: {
        color: '#fff'
      }
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      textStyle: {
        color: '#fff'
      }
    },
    series: [
      {
        name: data.name,
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#0a0e27',
          borderWidth: 2
        },
        label: {
          show: true,
          color: '#fff'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 20,
            fontWeight: 'bold'
          }
        },
        data: data.data
      }
    ]
  }
}

// 生成随机数据
export const generateRandomData = (count = 7) => {
  const categories = []
  const data = []
  for (let i = 0; i < count; i++) {
    categories.push(`数据${i + 1}`)
    data.push(Math.floor(Math.random() * 1000) + 100)
  }
  return { categories, data }
}
// 获取商品销售情况HTML页面
export const getChartHtml = () => {
  const chartId = 'chart_' + Math.random().toString(36).substr(2, 9)
  const option = JSON.stringify({
    "animation": true,
    "animationThreshold": 2000,
    "animationDuration": 1000,
    "animationEasing": "cubicOut",
    "animationDelay": 0,
    "animationDurationUpdate": 300,
    "animationEasingUpdate": "cubicOut",
    "animationDelayUpdate": 0,
    "aria": {
      "enabled": false
    },
    "color": [
      "#5470c6",
      "#91cc75",
      "#fac858",
      "#ee6666",
      "#73c0de",
      "#3ba272",
      "#fc8452",
      "#9a60b4",
      "#ea7ccc"
    ],
    "series": [
      {
        "type": "bar",
        "name": "商家A",
        "legendHoverLink": true,
        "data": [5, 20, 36, 10, 75, 90],
        "realtimeSort": false,
        "showBackground": false,
        "stackStrategy": "samesign",
        "cursor": "pointer",
        "barMinHeight": 0,
        "barCategoryGap": "20%",
        "barGap": "30%",
        "large": false,
        "largeThreshold": 400,
        "seriesLayoutBy": "column",
        "datasetIndex": 0,
        "clip": true,
        "zlevel": 0,
        "z": 2,
        "label": {
          "show": true,
          "margin": 8,
          "valueAnimation": false
        }
      },
      {
        "type": "bar",
        "name": "商家B",
        "legendHoverLink": true,
        "data": [15, 25, 16, 55, 48, 8],
        "realtimeSort": false,
        "showBackground": false,
        "stackStrategy": "samesign",
        "cursor": "pointer",
        "barMinHeight": 0,
        "barCategoryGap": "20%",
        "barGap": "30%",
        "large": false,
        "largeThreshold": 400,
        "seriesLayoutBy": "column",
        "datasetIndex": 0,
        "clip": true,
        "zlevel": 0,
        "z": 2,
        "label": {
          "show": true,
          "margin": 8,
          "valueAnimation": false
        }
      }
    ],
    "legend": [
      {
        "data": ["商家A", "商家B"],
        "selected": {},
        "show": true,
        "padding": 5,
        "itemGap": 10,
        "itemWidth": 25,
        "itemHeight": 14,
        "backgroundColor": "transparent",
        "borderColor": "#ccc",
        "borderRadius": 0,
        "pageButtonItemGap": 5,
        "pageButtonPosition": "end",
        "pageFormatter": "{current}/{total}",
        "pageIconColor": "#2f4554",
        "pageIconInactiveColor": "#aaa",
        "pageIconSize": 15,
        "animationDurationUpdate": 800,
        "selector": false,
        "selectorPosition": "auto",
        "selectorItemGap": 7,
        "selectorButtonGap": 10
      }
    ],
    "tooltip": {
      "show": true,
      "trigger": "item",
      "triggerOn": "mousemove|click",
      "axisPointer": {
        "type": "line"
      },
      "showContent": true,
      "alwaysShowContent": false,
      "showDelay": 0,
      "hideDelay": 100,
      "enterable": false,
      "confine": false,
      "appendToBody": false,
      "transitionDuration": 0.4,
      "textStyle": {
        "fontSize": 14
      },
      "borderWidth": 0,
      "padding": 5,
      "order": "seriesAsc"
    },
    "xAxis": [
      {
        "name": "商品",
        "show": true,
        "scale": false,
        "nameLocation": "end",
        "nameGap": 15,
        "inverse": false,
        "offset": 0,
        "splitNumber": 5,
        "minInterval": 0,
        "splitLine": {
          "show": true,
          "lineStyle": {
            "show": true,
            "width": 1,
            "opacity": 1,
            "curveness": 0,
            "type": "solid"
          }
        },
        "animation": true,
        "animationThreshold": 2000,
        "animationDuration": 1000,
        "animationEasing": "cubicOut",
        "animationDelay": 0,
        "animationDurationUpdate": 300,
        "animationEasingUpdate": "cubicOut",
        "animationDelayUpdate": 0,
        "data": ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
      }
    ],
    "yAxis": [
      {
        "name": "销量",
        "show": true,
        "scale": false,
        "nameLocation": "end",
        "nameGap": 15,
        "inverse": false,
        "offset": 0,
        "splitNumber": 5,
        "minInterval": 0,
        "splitLine": {
          "show": true,
          "lineStyle": {
            "show": true,
            "width": 1,
            "opacity": 1,
            "curveness": 0,
            "type": "solid"
          }
        },
        "animation": true,
        "animationThreshold": 2000,
        "animationDuration": 1000,
        "animationEasing": "cubicOut",
        "animationDelay": 0,
        "animationDurationUpdate": 300,
        "animationEasingUpdate": "cubicOut",
        "animationDelayUpdate": 0
      }
    ],
    "title": [
      {
        "show": true,
        "text": "商品销售情况",
        "target": "blank",
        "subtarget": "blank",
        "padding": 5,
        "itemGap": 10,
        "textAlign": "auto",
        "textVerticalAlign": "auto",
        "triggerEvent": false
      }
    ]
  }, null, 2)

  // 修改 option，添加更好的适配配置
  const enhancedOption = JSON.parse(option)
  enhancedOption.grid = {
    left: '10%',
    right: '8%',
    top: '15%',
    bottom: '12%',
    containLabel: true
  }
  
  const finalOption = JSON.stringify(enhancedOption, null, 2)

  return `
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商品销售情况</title>
    <script type="text/javascript" src="https://assets.pyecharts.org/assets/v5/echarts.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        html, body {
            width: 100%;
            height: 100%;
            overflow: hidden;
            background: transparent;
        }
        .chart-container {
            width: 100%;
            height: 100%;
            min-width: 0;
            min-height: 0;
            position: relative;
        }
    </style>
</head>
<body>
    <div id="${chartId}" class="chart-container"></div>
    <script>
        (function() {
            var chartElement = document.getElementById('${chartId}');
            if (!chartElement) return;
            
            var chart = null;
            var resizeTimer = null;
            
            function initChart() {
                if (chart && !chart.isDisposed()) {
                    chart.dispose();
                }
                
                chart = echarts.init(
                    chartElement, 
                    null, 
                    {renderer: 'canvas', locale: 'ZH'}
                );
                
                var option = ${finalOption};
                chart.setOption(option, true);
                
                // 立即执行一次 resize
                resizeChart();
            }
            
            // 窗口大小改变时自动调整（防抖）
            function resizeChart() {
                if (chart && !chart.isDisposed()) {
                    clearTimeout(resizeTimer);
                    resizeTimer = setTimeout(function() {
                        try {
                            chart.resize({
                                width: chartElement.clientWidth,
                                height: chartElement.clientHeight
                            });
                        } catch(e) {
                            console.warn('Chart resize error:', e);
                        }
                    }, 50);
                }
            }
            
            // 初始化图表
            if (document.readyState === 'loading') {
                document.addEventListener('DOMContentLoaded', initChart);
            } else {
                initChart();
            }
            
            window.addEventListener('resize', resizeChart);
            
            // 使用 ResizeObserver 监听容器大小变化
            if (window.ResizeObserver) {
                var resizeObserver = new ResizeObserver(function(entries) {
                    for (var i = 0; i < entries.length; i++) {
                        resizeChart();
                    }
                });
                resizeObserver.observe(chartElement);
            }
            
            // 确保 ECharts 库加载完成后再初始化
            if (typeof echarts === 'undefined') {
                var checkEcharts = setInterval(function() {
                    if (typeof echarts !== 'undefined') {
                        clearInterval(checkEcharts);
                        initChart();
                    }
                }, 100);
                
                setTimeout(function() {
                    clearInterval(checkEcharts);
                }, 5000);
            }
        })();
    </script>
</body>
</html>
  `
}

// 获取库存水平与采购水平月度变化HTML页面
export const getInventoryProcurementHtml = () => {
  const chartId = 'chart_' + Math.random().toString(36).substr(2, 9)
  const option = {
    "backgroundColor": "transparent",
    "tooltip": {
      "trigger": "axis",
      "axisPointer": { "type": "cross" },
      "backgroundColor": "rgba(0, 0, 0, 0.8)",
      "borderColor": "#1890ff",
      "textStyle": { "color": "#fff" }
    },
    "legend": {
      "data": ["采购数量", "库存数量"],
      "textStyle": { "color": "#fff" },
      "top": 10
    },
    "grid": {
      "left": "10%",
      "right": "10%",
      "top": "20%",
      "bottom": "15%",
      "containLabel": true
    },
    "xAxis": {
      "type": "category",
      "data": ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
      "axisLine": { "lineStyle": { "color": "#1890ff" } },
      "axisLabel": { "color": "#fff" }
    },
    "yAxis": [
      {
        "type": "value",
        "name": "采购数量",
        "axisLine": { "lineStyle": { "color": "#1890ff" } },
        "axisLabel": { "color": "#fff" },
        "splitLine": { "lineStyle": { "color": "rgba(24, 144, 255, 0.1)" } }
      },
      {
        "type": "value",
        "name": "库存数量",
        "axisLine": { "lineStyle": { "color": "#1890ff" } },
        "axisLabel": { "color": "#fff" },
        "splitLine": { "show": false }
      }
    ],
    "series": [
      {
        "name": "采购数量",
        "type": "bar",
        "data": [5075, 4420, 4437, 5222, 4058, 3751, 3903, 1825, 4100, 3900, 4200, 4500],
        "itemStyle": {
          "color": {
            "type": "linear",
            "x": 0,
            "y": 0,
            "x2": 0,
            "y2": 1,
            "colorStops": [
              { "offset": 0, "color": "#52c41a" },
              { "offset": 1, "color": "#1890ff" }
            ]
          }
        },
        "label": {
          "show": true,
          "position": "top",
          "color": "#fff"
        }
      },
      {
        "name": "库存数量",
        "type": "line",
        "yAxisIndex": 1,
        "data": [25000, 23000, 28000, 27000, 24000, 22000, 26000, 21000, 25000, 23000, 27000, 29000],
        "lineStyle": { "color": "#ff9800", "width": 2 },
        "itemStyle": { "color": "#ff9800" }
      }
    ]
  }
  
  const optionStr = JSON.stringify(option, null, 2)

  return `
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>库存水平与采购水平月度变化</title>
    <script type="text/javascript" src="https://assets.pyecharts.org/assets/v5/echarts.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        html, body {
            width: 100%;
            height: 100%;
            overflow: hidden;
            background: transparent;
        }
        .chart-container {
            width: 100%;
            height: 100%;
            min-width: 0;
            min-height: 0;
            position: relative;
        }
    </style>
</head>
<body>
    <div id="${chartId}" class="chart-container"></div>
    <script>
        (function() {
            var chartElement = document.getElementById('${chartId}');
            if (!chartElement) return;
            
            var chart = null;
            var resizeTimer = null;
            
            function initChart() {
                if (chart && !chart.isDisposed()) {
                    chart.dispose();
                }
                
                chart = echarts.init(
                    chartElement, 
                    null, 
                    {renderer: 'canvas', locale: 'ZH'}
                );
                
                var option = ${optionStr};
                chart.setOption(option, true);
                
                // 立即执行一次 resize
                resizeChart();
            }
            
            // 窗口大小改变时自动调整（防抖）
            function resizeChart() {
                if (chart && !chart.isDisposed()) {
                    clearTimeout(resizeTimer);
                    resizeTimer = setTimeout(function() {
                        try {
                            chart.resize({
                                width: chartElement.clientWidth,
                                height: chartElement.clientHeight
                            });
                        } catch(e) {
                            console.warn('Chart resize error:', e);
                        }
                    }, 50);
                }
            }
            
            // 初始化图表
            if (document.readyState === 'loading') {
                document.addEventListener('DOMContentLoaded', initChart);
            } else {
                initChart();
            }
            
            window.addEventListener('resize', resizeChart);
            
            // 使用 ResizeObserver 监听容器大小变化
            if (window.ResizeObserver) {
                var resizeObserver = new ResizeObserver(function(entries) {
                    for (var i = 0; i < entries.length; i++) {
                        resizeChart();
                    }
                });
                resizeObserver.observe(chartElement);
            }
            
            // 确保 ECharts 库加载完成后再初始化
            if (typeof echarts === 'undefined') {
                var checkEcharts = setInterval(function() {
                    if (typeof echarts !== 'undefined') {
                        clearInterval(checkEcharts);
                        initChart();
                    }
                }, 100);
                
                setTimeout(function() {
                    clearInterval(checkEcharts);
                }, 5000);
            }
        })();
    </script>
</body>
</html>
  `
}
